package com.truyentranh.modules.tamdiem;

import java.io.Serializable;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.controls.DataCachedControl;
import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.data.HaiBLModule;
import com.truyentranh.data.TamDiemDetailModuleData;
import com.truyentranh.data.TamDiemDetailTopicData;
import com.truyentranh.main.AdsBussiness;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.GirlRequester;
import com.truyentranh.requester.TamDiemRequester;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.Logger;

public class TamDiemDetailModulesActivity extends Activity implements OnScrollListener, RequestListener, OnItemClickListener {

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;

	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	LinearLayout loadingMore = null;
	GridView imageListView = null;

	TamDiemDetailModulesRenderAdapter tamDiemRenderAdapter = null;
	String idModules = "";
	String nameTitle = "";
	boolean isLoading = false;

	long requestId = -1;
	
	public static final int TAMDIEM = 111;
	public static final int GIRLDETAIL = 222;
	private int moduleLoaded = -1;
	private String hrefLoaded = "";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			idModules = extras.getString("ID");
			nameTitle = extras.getString("NAME");
			moduleLoaded = extras.getInt("moduleLoaded");
			hrefLoaded = extras.getString("href");
			
			Logger.logMe("id = " + idModules);
		}
		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.tamdiem_detail_module_activity_layout);
		init();

		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		loadingMore = (LinearLayout) findViewById(R.id.loadMore);
		loadingError.setVisibility(View.INVISIBLE);

		mainContent = (LinearLayout) findViewById(R.id.mainContent);

		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (GridView) findViewById(R.id.imageListView);
		
		if(moduleLoaded == GIRLDETAIL)
			imageListView.setNumColumns(3);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText(nameTitle);

		Button button = (Button) findViewById(R.id.btnMoreFunctions);
		button.setBackgroundResource(R.drawable.refresh_indicator);
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				runOnUiThread(new Runnable() {
					public void run() {
						if (!isLoading) {
							// tamDiemRenderAdapter.clearData();

							isLoading = true;

							imageListView.setVisibility(View.INVISIBLE);
							loadingError.setVisibility(View.GONE);
							loadingPage.setVisibility(View.VISIBLE);

							TamDiemRequester requester = TamDiemRequester.getDetailModules(idModules, page, TamDiemDetailModulesActivity.this);
							requestId = AppSettingParams.nextRequestId();
							requester.setRequestId(requestId);
							APIRequestWorker.getInstance().addAPIRequest(requester);
						}
					}
				});
			}
		});

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					requestId = -1;
					DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
					finish();
				}
			});
		}
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	@Override
	protected void onDestroy() {
		APIRequestWorker.getInstance().clearAllRequests();
		DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
		super.onDestroy();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			requestId = -1;
			DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		onStartUp();
	}

	int page = 1;

	private void onStartUp() {
		
		loadingPage.setVisibility(View.VISIBLE);
		
		loadingError.setVisibility(View.INVISIBLE);
		loadingMore.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);
		mainContent.setVisibility(View.INVISIBLE);
		prviewTamDiem.setVisibility(View.INVISIBLE);
		imageListView.setVisibility(View.INVISIBLE);
		
		
		ArrayList<TamDiemDetailModuleData> cachedList = (ArrayList<TamDiemDetailModuleData>) DataCachedControl.getInstance().getCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
		if(cachedList != null && !cachedList.isEmpty()){
			fillDatatoGridView(cachedList);
		} else {
			Request requester = null;
			if(moduleLoaded == GIRLDETAIL){
				requester = GirlRequester.getDetail(hrefLoaded, this);
			} else {
				requester = TamDiemRequester.getDetailModules(idModules, page, this);
			}		
			
			requestId = AppSettingParams.nextRequestId();
			requester.setRequestId(requestId);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}		
	}

	void init() {
	}

	void fillDatatoGridView(final ArrayList<TamDiemDetailModuleData> requestedDataList) {

		if (imageListView != null) {
			runOnUiThread(new Runnable() {

				public void run() {
					DataCachedControl.getInstance().putCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST, requestedDataList);
					if (tamDiemRenderAdapter == null) {
						tamDiemRenderAdapter = new TamDiemDetailModulesRenderAdapter(TamDiemDetailModulesActivity.this, 1, 1, requestedDataList);
						imageListView.setAdapter(tamDiemRenderAdapter);
					} else {
						tamDiemRenderAdapter.setBlockList(requestedDataList);
						tamDiemRenderAdapter.notifyDataSetChanged();
					}

					imageListView.setOnItemClickListener(TamDiemDetailModulesActivity.this);
					imageListView.setOnScrollListener(TamDiemDetailModulesActivity.this);

					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.GONE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.VISIBLE);
					prviewTamDiem.setVisibility(View.VISIBLE);
					imageListView.setVisibility(View.VISIBLE);

					isLoading = false;

					doAdsByServer();
				}
			});

		}
	}

	ArrayList<TamDiemDetailModuleData> requestedDataList;
	public void onRequestComplete(final Request request) {
		Logger.logMe("requestId = " + requestId);
		
		// TODO Auto-generated method stub
		if (request instanceof TamDiemRequester && requestId == request.getRequestId()) {
			final ArrayList<TamDiemDetailModuleData> requestedDataList = ((TamDiemRequester) request).getDataDetailList();
			fillDatatoGridView(requestedDataList);
		} else if(request instanceof GirlRequester){
			requestedDataList = ((GirlRequester) request).getTamDiemDetailModuleDataDatas();
			fillDatatoGridView(requestedDataList);
		}
	}

	public void onRequestFailed(String errorMsg, Request request) {
		if (request instanceof TamDiemRequester && requestId == request.getRequestId()) {
			runOnUiThread(new Runnable() {

				public void run() {
					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.VISIBLE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.GONE);
					prviewTamDiem.setVisibility(View.GONE);
					imageListView.setVisibility(View.GONE);

					isLoading = false;

					doAdsByServer();
				}
			});
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		Logger.logMe("1");
		if (tamDiemRenderAdapter != null) {Logger.logMe("2");
			TamDiemDetailModuleData diemMetalData = tamDiemRenderAdapter.getItem(index);Logger.logMe("3");
			if (moduleLoaded != GIRLDETAIL) {
				final String href = diemMetalData.getHref();
				if (href != null && !"".equals(href)) {
					Intent intent = new Intent(getApplication(), TamDiemDetailTopicActivity.class);
					intent.putExtra("href", href);
					intent.putExtra("NAME", diemMetalData.getTitle());

					startActivity(intent);
				}
			} else {		Logger.logMe("4");		
				TamDiemDetailTopicData detailTopicData = new TamDiemDetailTopicData();
				detailTopicData.setTitle(diemMetalData.title);
				detailTopicData.setDescrition(diemMetalData.title);
				detailTopicData.setBaseURL("");
				
				if(requestedDataList != null){
					for(int i = 0 , n = requestedDataList.size() ; i < n ;i++){
						TamDiemDetailModuleData data = requestedDataList.get(i);
						HaiBLMetalData blMetalData = new HaiBLMetalData();
						blMetalData.setTYPE(HaiBLModule.TAMDIEM);
						if(AppSettingParams.isUseBigImage()){
							blMetalData.setImageUrl(data.bigsrc);
						} else {
							blMetalData.setImageUrl(data.src);
						}						
						blMetalData.setTitleDescription(diemMetalData.title);
						detailTopicData.appendHaiBlMetalData(blMetalData);
					}
					
					DataCachedControl.getInstance().putCached(DataCachedControl.GIRL_IMAGE_LIST, detailTopicData);
					Intent intent = new Intent(getApplication(), TamDiemDetailTopicActivity.class);	
					intent.putExtra("index", index);
					startActivity(intent);
				}
			}
		}
			
	}

	RequestListener listenerLoadMore = new RequestListener() {

		public void onRequestFailed(String errorMsg, Request request) {
			runOnUiThread(new Runnable() {

				public void run() {
					// TODO Auto-generated method stub
					if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
						loadingMore.setVisibility(View.GONE);
				}
			});

		}

		public void onRequestComplete(Request request) {
			if (request instanceof TamDiemRequester) {
				final ArrayList<TamDiemDetailModuleData> requestedDataList = ((TamDiemRequester) request).getDataDetailList();
				if (imageListView != null) {
					runOnUiThread(new Runnable() {

						public void run() {
							if (tamDiemRenderAdapter != null) {

								ArrayList<TamDiemDetailModuleData> cachedList = (ArrayList<TamDiemDetailModuleData>) DataCachedControl.getInstance().getCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
								if (cachedList != null && requestedDataList != null) {
									final int size = requestedDataList.size();
									for (int i = 0; i < size; i++) {
										cachedList.add(requestedDataList.get(i));
									}
								}
								tamDiemRenderAdapter.appendData(requestedDataList);
							}

							isLoading = false;

							if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
								loadingMore.setVisibility(View.GONE);
						}
					});

				}
			}

		}
	};

	public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		if (moduleLoaded != GIRLDETAIL && !isLoading && tamDiemRenderAdapter != null && !tamDiemRenderAdapter.isEmpty() && (lastInScreen == totalItemCount) && (page < 100)) {
			if (loadingMore != null && loadingMore.getVisibility() != View.VISIBLE)
				loadingMore.setVisibility(View.VISIBLE);
			isLoading = true;
			page += 1;
			TamDiemRequester requester = TamDiemRequester.getDetailModules(idModules, page, listenerLoadMore);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
}
